/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.druid.catalog;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import org.apache.druid.catalog.model.ResolvedTable;
import org.apache.druid.catalog.model.TableDefnRegistry;
import org.apache.druid.catalog.model.TableId;
import org.apache.druid.catalog.model.TableMetadata;
import org.apache.druid.catalog.model.TableSpec;

import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class MapMetadataCatalog implements MetadataCatalog
{
  private final TableDefnRegistry registry;

  private final Map<TableId, TableMetadata> metadata = new HashMap<>();

  public MapMetadataCatalog(ObjectMapper mapper)
  {
    this.registry = new TableDefnRegistry(mapper);
  }

  public void addSpec(TableId id, TableSpec spec)
  {
    metadata.put(id, TableMetadata.newTable(id, spec));
  }

  @Nullable
  @Override
  public TableMetadata getTable(TableId tableId)
  {
    return metadata.get(tableId);
  }

  @Nullable
  @Override
  public ResolvedTable resolveTable(TableId tableId)
  {
    final TableMetadata tableMetadata = metadata.get(tableId);
    if (tableMetadata == null) {
      return null;
    }
    return registry.resolve(tableMetadata.spec());
  }

  @Override
  public List<TableMetadata> tables(String schemaName)
  {
    return ImmutableList.copyOf(metadata.values());
  }

  @Override
  public Set<String> tableNames(String schemaName)
  {
    return metadata.keySet()
                   .stream()
                   .filter(x -> x.schema().equals(schemaName))
                   .map(TableId::name)
                   .collect(Collectors.toSet());
  }
}
